package cn.tedu.store.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.tedu.store.entity.Address;
import cn.tedu.store.service.IAddressService;
import cn.tedu.store.util.ResponseResult;

@RestController
@RequestMapping("addresses")
public class AddressController extends BaseController {
	@Autowired
	private IAddressService addressService;
	

	
	@RequestMapping("create_address")
	public ResponseResult<Void> createAddress(Address address,HttpSession session){
		//从Session中获取uid，方法来自父类
		Integer uid = getUidFromSession(session);
		//将uid封装到address中，供AddressServiceImpl使用
		address.setUid(uid);
		//从Session中获取username，方法来自父类
		String username = getUsernameFromSession(session);
		//执行创建收货地址
		addressService.createAddress(address, username);
		//返回执行成功，执行不成功的都在BaseController中处理了，这里只考虑成功的情况
		return new ResponseResult<>(SUCCESS);
		
	}
	
	
	@RequestMapping("/") //返回的是集合，行业默认用 / 表示访问路径，这是行业约定成俗的事情
	public ResponseResult<List<Address>> getByUid(HttpSession session){
		//从Session中获取uid
		Integer uid = Integer.valueOf(session.getAttribute("uid").toString());
		//执行业务层方法，得到收货地址列表
		List<Address> data = addressService.getByUid(uid);
		//返回收货地址列表
		return new ResponseResult<>(SUCCESS,data);
	}

	
	@RequestMapping("{aid}/set_default")
	public ResponseResult<Void> setDefault(
			//RESTful 风格 参数必须添加@PathVariable("参数")注解，参数必须与路径中的{参数}一致
			@PathVariable("aid") Integer aid,
			HttpSession session
			){
		//从Session中获取uid和username
		Integer uid = getUidFromSession(session);
		String username = getUsernameFromSession(session);
		//执行设置默认地址
		addressService.setDefault(aid, uid, username);
		//响应
		return new ResponseResult<Void>(SUCCESS);
	}
	
	@RequestMapping("/delete")
	public ResponseResult<Void> delete(
			HttpSession session,
			Integer aid){
		//从Session中获取uid和username
		Integer uid = getUidFromSession(session);
		String username = getUsernameFromSession(session);
		//执行删除
		addressService.delete(aid, uid, username);
		//响应
		return new ResponseResult<Void>(SUCCESS);
	}
	
}
